<template>
  <div>
    <el-form inline :model="froUserQuery" ref="queryFormRef">
      <el-form-item>
        <el-input placeholder="关键字" v-model="froUserQuery.keywords"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="froUserQuery.status"
            placeholder="请选择状态"
            style="width: 240px"
        >
          <el-option label="正常" :value="0"/>
          <el-option label="禁用" :value="1"/>
          <el-option label="全部" :value="-1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" @click="resetQuery(queryFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button size="small" :icon="Plus" @click="dialogVisible = true">新增</el-button>
    <el-button :icon="Download" size="small">导入</el-button>
    <el-button :icon="Upload" size="small">导出</el-button>
    <el-table :data="froUserPage.list" v-loading="loading">
      <el-table-column prop="userId" label="用户ID"/>
      <el-table-column prop="userName" label="用户名"/>
      <el-table-column prop="nickname" label="昵称"/>
      <el-table-column prop="avatar" label="头像">
        <template #default="scope">
          <el-avatar
              :src="scope.row.avatar"
              style="width: 50px; height: 50px; border-radius: 50%"
          />
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column prop="sex" label="性别">
        <template #default="scope">
          {{ scope.row.sex === 0 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间">
        <template #default="scope">
          {{ formatDate(scope.row.createTime, "YYYY-MM-DD") }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <el-button icon="EditPen" type="warning" size="small" @click="openModify(scope.row.userId)">
            修改
          </el-button>
          <el-divider direction="vertical"/>
          <el-button icon="Delete" type="danger" size="small" @click="deleteFroUser(scope.row.userId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex-end">
      <el-pagination
          v-model:page-size="froUserQuery.pageSize"
          v-model:current-page="froUserQuery.pageNum"
          layout="prev, pager, next"
          :total="froUserPage.total"
      />
    </div>
    <el-dialog v-model="dialogVisible" :title="isAdd ? '新增' : '修改'" width="500">
      <el-form :model="froUser" :rules="rules" ref="froUserFormRef" label-width="120px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="froUser.userId" disabled/>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="froUser.userName"/>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="froUser.nickname"/>
        </el-form-item>
        <el-form-item label="专业" prop="nickname">
          <el-input v-model="froUser.major"/>
        </el-form-item>
        <el-form-item label="学院" prop="nickname">
          <el-input v-model="froUser.college"/>
        </el-form-item>
        <el-form-item label="学号" prop="nickname">
          <el-input v-model="froUser.studentId"/>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <avatar-upload :imageUrl="froUser.avatar" @filePath="getFilePath"></avatar-upload>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="froUser.phone"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="froUser.status" placeholder="请选择状态">
            <el-option label="启用" value="active"/>
            <el-option label="禁用" value="inactive"/>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="froUser.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="注册时间" prop="createTime">
          <el-date-picker
              v-model="froUser.createTime"
              type="datetime"
              placeholder="选择日期时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(froUserFormRef)">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref, watch} from "vue";
import type {FormInstance, FormRules} from "element-plus";
import {Search, Refresh, EditPen, Delete, Plus, Upload, Download} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import type {FroUser} from "@/api/front/user/type";
import {
  reqGetFroUserList,
  reqCreateFroUser,
  reqModifyFroUser,
  reqGetFroUserInfo,
  reqDeleteFroUser
} from "@/api/front/user";
import AvatarUpload from "@/components/common/AvatarUpload.vue";
import {formatDate} from "@/util";

let froUserQuery = reactive({
  pageNum: 1,
  pageSize: 7,
  keywords: "",
  status: -1,
  total: 0,
});
let froUser = reactive<FroUser>({
  userId: "",
  userName: "",
  studentId:'',
  nickname: '',
  avatar: "",
  password: "",
  phone: "",
  status: 0,
  sex: 0,
  createTime: null,
  major: '',
  grade: '',
  email:'',
  college:''
});
let queryFormRef = ref<FormInstance>()
let loading = ref(true);
let dialogVisible = ref(false);
let isAdd = ref(true);
let froUserFormRef = ref();
let froUserPage = reactive({
  pageNum: 1,
  list: [],
  total: 0,
})
const rules = reactive<FormRules<FroUser>>({
  userName: [{required: true, message: "请输入用户昵称", trigger: "blur"}],
  // phone: [
  //   {required: true, message: "请输入手机号", trigger: "blur"},
  //   {pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号", trigger: "blur"},
  // ],
  status: [{required: true, message: "请选择状态", trigger: "change"}],
  sex: [{required: true, message: "请选择性别", trigger: "change"}],
});

let resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const openModify = (userId: string) => {
  reqGetFroUserInfo(userId).then((res) => {
    Object.assign(froUser, res.data);
    dialogVisible.value = true;
  });
};
const getFilePath = (filePath: string) => {
  froUser.avatar = filePath;
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isAdd.value) {
        reqCreateFroUser(froUser)
            .finally(() => {
              dialogVisible.value = false;
            });
      } else {
        reqModifyFroUser(froUser)
            .finally(() => {
              dialogVisible.value = false;
            });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
  getUserList();
};
let deleteFroUser = (userId: string) => {
  ElMessageBox.confirm("确定删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  } as  any).then(() => {
    reqDeleteFroUser(userId).then(() => {
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
      getUserList();
    });
  });
}

function getUserList() {
  reqGetFroUserList(froUserQuery).then((res) => {
    Object.assign(froUserPage, res.data)
    loading.value = false;
  });
}

watch([() => froUserQuery.pageNum, () => froUserQuery.pageSize], () => {
  getUserList()
})

onMounted(() => {
  getUserList();
});
</script>
